package com.xyht.medicine_management_system.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.modules.user.entity.MmsUser;
import com.xyht.medicine_management_system.modules.user.entity.MmsUserExamine;
import com.xyht.medicine_management_system.modules.user.entity.req.MmsUserExamineAllowReq;
import com.xyht.medicine_management_system.modules.user.entity.req.MmsUserExamineApplyReq;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsUserExamineResp;
import com.xyht.medicine_management_system.modules.user.entity.resp.UserinfoResp;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserExamineMapper;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserMapper;
import com.xyht.medicine_management_system.modules.user.service.MmsUserExamineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.medicine_management_system.modules.user.constant.ApplyTypeConstant.APPLY_TYPE_COMPANY;
import static com.xyht.medicine_management_system.modules.user.constant.ApplyTypeConstant.APPLY_TYPE_PERSON;
import static com.xyht.medicine_management_system.modules.user.constant.AuthStatusConstant.*;
import static com.xyht.medicine_management_system.modules.user.constant.ExamineStatusConstant.*;
import static com.xyht.medicine_management_system.modules.user.constant.IsEntrustConstant.IS_ENTRUST_FALSE;
import static com.xyht.medicine_management_system.modules.user.constant.IsEntrustConstant.IS_ENTRUST_TRUE;
import static com.xyht.medicine_management_system.modules.user.constant.UserTypeConstant.*;

/**
 * <p>
 * 用户审核表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-11-16
 */
@Service
public class MmsUserExamineServiceImpl extends ServiceImpl<MmsUserExamineMapper, MmsUserExamine> implements MmsUserExamineService {
    @Resource
    private MmsUserExamineMapper mmsUserExamineMapper;
    @Resource
    private MmsUserMapper mmsUserMapper;


    @Override
    @Transactional
    public ResponseResult AuthExamineApply(MmsUserExamineApplyReq applyReq, String user_id) {
        List<MmsUserExamine> examineList = mmsUserExamineMapper.selectList(new LambdaQueryWrapper<MmsUserExamine>()
                .eq(MmsUserExamine::getUserId, user_id)
                .eq(MmsUserExamine::getExamineStatus, EXAMINE_STATUS_WAITING));
        if (examineList != null && examineList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.USER_EXAMINE_EXIST);
        }

        MmsUser mmsUser = mmsUserMapper.selectById(user_id);
        if (mmsUser.getUserType().equals(USER_TYPE_ADMIN)){
            return CommonResult.failed(CommonCodeEnum.PERMISSION_DENY);
        }

        if (isNullOrEmpty(applyReq.getApplyType(), applyReq.getIsEntrust(), applyReq.getPersonIdCardBack(),
                applyReq.getPersonIdCardFront(), applyReq.getPersonName(),
                applyReq.getPersonIdCard())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (!applyReq.getApplyType().equals(APPLY_TYPE_PERSON) && !applyReq.getApplyType().equals(APPLY_TYPE_COMPANY)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (applyReq.getApplyType().equals(APPLY_TYPE_COMPANY)) {
            if (isNullOrEmpty(applyReq.getLicense(), applyReq.getBusinessLicense(),
                    applyReq.getCompanyName(), applyReq.getLicenseNum())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        if (applyReq.getIsEntrust().equals(IS_ENTRUST_TRUE)) {
            if (isNullOrEmpty(applyReq.getProxyFile(), applyReq.getProxyIdCardFront(), applyReq.getProxyIdCardBack(),
                    applyReq.getProxyName(), applyReq.getProxyIdCard())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //添加认证申请
        MmsUserExamine addUserExamine = new MmsUserExamine();
        if (applyReq.getApplyType().equals(APPLY_TYPE_PERSON)) {
            addUserExamine.setApplyType(APPLY_TYPE_PERSON);
            addUserExamine.setPersonIdCardBack(applyReq.getPersonIdCardBack());
            addUserExamine.setPersonIdCardFront(applyReq.getPersonIdCardFront());
            addUserExamine.setIsEntrust(IS_ENTRUST_FALSE);

        } else {
            if (applyReq.getIsEntrust().equals(IS_ENTRUST_TRUE)) {
                addUserExamine.setProxyFile(applyReq.getProxyFile());
                addUserExamine.setProxyIdCardFront(applyReq.getProxyIdCardFront());
                addUserExamine.setProxyIdCardBack(applyReq.getProxyIdCardBack());
                addUserExamine.setIsEntrust(IS_ENTRUST_TRUE);
                addUserExamine.setProxyName(applyReq.getProxyName());
                addUserExamine.setProxyIdCard(applyReq.getProxyIdCard());
            } else {
                addUserExamine.setIsEntrust(IS_ENTRUST_FALSE);
            }

            addUserExamine.setLicense(applyReq.getLicense());
            addUserExamine.setBusinessLicense(applyReq.getBusinessLicense());
            addUserExamine.setCompanyName(applyReq.getCompanyName());
            addUserExamine.setLicenseNum(applyReq.getLicenseNum());

            addUserExamine.setApplyType(APPLY_TYPE_COMPANY);
            addUserExamine.setPersonIdCardBack(applyReq.getPersonIdCardBack());
            addUserExamine.setPersonIdCardFront(applyReq.getPersonIdCardFront());

        }
        addUserExamine.setPersonName(applyReq.getPersonName());
        addUserExamine.setPersonIdCard(applyReq.getPersonIdCard());
        addUserExamine.setExamineStatus(EXAMINE_STATUS_WAITING);
        addUserExamine.setUserId(user_id);
        mmsUserExamineMapper.insert(addUserExamine);

        //修改用户认证状态
        MmsUser updateUser = new MmsUser();
        updateUser.setId(user_id);
        updateUser.setAuthStatus(AUTH_STATUS_AUTH_DOING);
        mmsUserMapper.updateById(updateUser);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getApplyHistory(Integer pageNum, Integer pageSize, String user_id) {
        Page<MmsUserExamine> page = new Page<>(pageNum, pageSize);
        mmsUserExamineMapper.selectPage(page, new LambdaQueryWrapper<MmsUserExamine>()
                .eq(MmsUserExamine::getUserId, user_id)
                .orderByDesc(MmsUserExamine::getCreateTime));
        List<MmsUserExamineResp> userExamineRespList = page.getRecords()
                .stream()
                .map(mmsUserExamine -> {
                    MmsUserExamineResp userExamineResp = new MmsUserExamineResp();
                    BeanUtils.copyProperties(mmsUserExamine, userExamineResp);
                    return userExamineResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(userExamineRespList, total);
    }

    @Override
    public ResponseResult getExamineDetail(String id) {
        MmsUserExamine mmsUserExamine = mmsUserExamineMapper.selectById(id);
        if (mmsUserExamine == null){
            return CommonResult.failed(CommonCodeEnum.USER_EXAMINE_NOT_EXIST);
        }

        MmsUserExamineResp userExamineResp = new MmsUserExamineResp();
        BeanUtils.copyProperties(mmsUserExamine, userExamineResp);

        MmsUser applyUser = mmsUserMapper.selectById(mmsUserExamine.getUserId());
        if (applyUser != null) {
            UserinfoResp applyUserinfo = new UserinfoResp();
            BeanUtils.copyProperties(applyUser, applyUserinfo);
            userExamineResp.setApplyUserinfo(applyUserinfo);
        }

        MmsUser allowUser = mmsUserExamine.getExamineUser() == null ? null : mmsUserMapper.selectById(mmsUserExamine.getExamineUser());
        if (allowUser != null) {
            UserinfoResp allowUserinfo = new UserinfoResp();
            BeanUtils.copyProperties(allowUser, allowUserinfo);
            userExamineResp.setExamineUserinfo(allowUserinfo);
        }
        return CommonResult.success(userExamineResp);
    }

    @Override
    public ResponseResult getExamineList(Integer pageNum, Integer pageSize, Integer examineType,Integer applyType) {
        QueryWrapper<MmsUserExamine> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(examineType)){
            queryWrapper.lambda().eq(MmsUserExamine::getExamineStatus,examineType);
        }
        if (!isNullOrEmpty(applyType)){
            queryWrapper.lambda().eq(MmsUserExamine::getApplyType,applyType);
        }
        queryWrapper.lambda().orderByDesc(MmsUserExamine::getCreateTime);
        Page<MmsUserExamine> page = new Page<>(pageNum, pageSize);
        mmsUserExamineMapper.selectPage(page, queryWrapper);
        List<MmsUserExamineResp> userExamineRespList = page.getRecords()
                .stream()
                .map(mmsUserExamine -> {
                    MmsUserExamineResp userExamineResp = new MmsUserExamineResp();
                    BeanUtils.copyProperties(mmsUserExamine, userExamineResp);

                    MmsUser applyUser = mmsUserMapper.selectById(mmsUserExamine.getUserId());
                    if (applyUser != null) {
                        UserinfoResp applyUserinfo = new UserinfoResp();
                        BeanUtils.copyProperties(applyUser, applyUserinfo);
                        userExamineResp.setApplyUserinfo(applyUserinfo);
                    }

                    MmsUser allowUser = mmsUserExamine.getExamineUser() == null ? null : mmsUserMapper.selectById(mmsUserExamine.getExamineUser());
                    if (allowUser != null) {
                        UserinfoResp allowUserinfo = new UserinfoResp();
                        BeanUtils.copyProperties(allowUser, allowUserinfo);
                        userExamineResp.setExamineUserinfo(allowUserinfo);
                    }
                    return userExamineResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(userExamineRespList, total);
    }

    @Override
    @Transactional
    public ResponseResult allowUserApply(MmsUserExamineAllowReq allowReq, String user_id) {
        if (isNullOrEmpty(allowReq.getExamineStatus(), allowReq.getId(),allowReq.getQualificationType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (!allowReq.getExamineStatus().equals(EXAMINE_STATUS_PASS) && !allowReq.getExamineStatus().equals(EXAMINE_STATUS_DENY)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsUserExamine mmsUserExamine = mmsUserExamineMapper.selectById(allowReq.getId());
        if (mmsUserExamine == null){
            return CommonResult.failed(CommonCodeEnum.USER_EXAMINE_NOT_EXIST);
        }

        //审批用户认证申请
        MmsUserExamine updateUserExamine = new MmsUserExamine();
        updateUserExamine.setId(allowReq.getId());
        updateUserExamine.setExamineStatus(allowReq.getExamineStatus());
        updateUserExamine.setExamineOpinion(allowReq.getExamineOpinion());
        updateUserExamine.setExamineTime(new Date());
        updateUserExamine.setExamineUser(user_id);
        updateUserExamine.setQualificationType(allowReq.getQualificationType());

        mmsUserExamineMapper.updateById(updateUserExamine);

        //修改用户认证信息
        MmsUser updateUser = new MmsUser();
        updateUser.setId(mmsUserExamine.getUserId());
        if (allowReq.getExamineStatus().equals(EXAMINE_STATUS_PASS)){
            updateUser.setAuthStatus(AUTH_STATUS_AUTH);
            updateUser.setQualificationType(allowReq.getQualificationType());
        }else {
            updateUser.setAuthStatus(AUTH_STATUS_NOT_AUTH);
        }

        if (mmsUserExamine.getApplyType().equals(APPLY_TYPE_PERSON)){
            updateUser.setUserType(USER_TYPE_PERSON);
        }else {
            updateUser.setUserType(USER_TYPE_COMPANY);
        }

        mmsUserMapper.updateById(updateUser);
        return CommonResult.success();
    }
}
